
#include "nvs_system_cfg.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "utils_log.h"

static const char *TAG = "NVS_SYSTEM_CFG--->";

#define NVS_SYSTEM_FILE_NAME        "System_cfg"
#define NVS_SYSTEM_CONN_TYPE_KEY    "connection_type"

int GetNvsConnectionType(void *value, const int len)
{
    if (NULL == value){
        ESP_LOGE(TAG, "input params is invalid");
        LOG_TO_FILE("input params is invalid");
        return -1;
    }

    nvs_handle handle;
    esp_err_t err = nvs_open(NVS_SYSTEM_FILE_NAME, NVS_READWRITE, &handle);
    if (err != ESP_OK){
        ESP_LOGE(TAG, "open %s file failed:%s",NVS_SYSTEM_FILE_NAME, esp_err_to_name(err));
        LOG_TO_FILE("open %s file failed:%s",NVS_SYSTEM_FILE_NAME, esp_err_to_name(err));
        return -1;
    }
    
    err = nvs_get_blob(handle, NVS_SYSTEM_CONN_TYPE_KEY, value, &len);
    if (err != ESP_OK){
        ESP_LOGE(TAG, "get %s blob failed:%s",NVS_SYSTEM_CONN_TYPE_KEY, esp_err_to_name(err));
    }

    nvs_close(handle);

    return err;
}

int SetNvsConnectionType(const void *value, const int len)
{
    if (NULL == value){
        ESP_LOGE(TAG, "input params is invalid");
        LOG_TO_FILE("input params is invalid");
        return -1;
    }

    nvs_handle handle;
    esp_err_t err = nvs_open(NVS_SYSTEM_FILE_NAME, NVS_READWRITE, &handle);
    if (err != ESP_OK){
        ESP_LOGE(TAG, "open %s file failed:%s",NVS_SYSTEM_FILE_NAME, esp_err_to_name(err));
        LOG_TO_FILE("open %s file failed:%s",NVS_SYSTEM_FILE_NAME, esp_err_to_name(err));
        return -1;
    }
    
    err = nvs_set_blob(handle, NVS_SYSTEM_CONN_TYPE_KEY, value, len);
    if (err != ESP_OK){
        ESP_LOGE(TAG, "set %s blob failed:%s",NVS_SYSTEM_CONN_TYPE_KEY, esp_err_to_name(err));
    }

    err = nvs_commit(handle);
    nvs_close(handle);

    return err;
}